package com.example.yiwei.crm.view.activity.jtCustomer;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.example.yiwei.crm.R;
import com.example.yiwei.crm.base.baseClass;
import com.example.yiwei.crm.data.GetCustumer;
import com.example.yiwei.crm.entity.CustomerMessageEntity;
import com.example.yiwei.crm.json.CoorCustomerJson;
import com.example.yiwei.crm.util.NetWorkUtils;
import com.example.yiwei.crm.view.Class.listviewClass.AutoListView;
import com.example.yiwei.crm.view.Class.listviewClass.ListViewAdapter;
import com.example.yiwei.crm.view.activity.JYCoordingActivity.SeacherCustomerActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class CustomerJZSeacherActivity extends AppCompatActivity implements AutoListView.OnRefreshListener,AutoListView.OnLoadListener {
    private ImageView btn_seacher;
    private ImageView im_back;
    private AutoListView listView;
    private PopupWindow mPopWindow;
    private String name,phone,cphone,yynumber;
    private int page = 1;
    private ListViewAdapter adapter;
    public static CustomerJZSeacherActivity b;
    private List<CustomerMessageEntity> list;
    private List<CustomerMessageEntity> alist;
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            List<CustomerMessageEntity> result = (List<CustomerMessageEntity>) msg.obj;
            switch (msg.what) {
                case AutoListView.REFRESH:
                    listView.onRefreshComplete();
                    if (list!=null){
                        list.clear();
                    }
                    if (list!=null){
                        list.addAll(result);
                    }else {
                        list = result;
                    }

                    break;
                case AutoListView.LOAD:
                    listView.onLoadComplete();
                    if (result!=null){
                        list.addAll(result);
                    }

                    break;
            }
            if (result!=null) {
//                listView.setResultSize(result.size());
            }else{
//                listView.setResultSize(0);
            }
            adapter.notifyDataSetChanged();

        }


    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_jzseacher);
        listView = (AutoListView) findViewById(R.id.customer_jz_seacher);
        im_back = (ImageView) findViewById(R.id.customer_jz_back);
        btn_seacher = (ImageView) findViewById(R.id.coor_yu_img_search);
        btn_seacher.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CustomerJZSeacherActivity.this,SeacherCustomerActivity.class);
                startActivity(intent);
            }
        });
        im_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        listView.setDivider(new ColorDrawable(Color.rgb(216, 216, 216)));
        listView.setDividerHeight(1);
        listView.setOnRefreshListener(this);
        listView.setOnLoadListener(this);
        b=this;
        name = getIntent().getStringExtra("name");
        phone = getIntent().getStringExtra("phone");
        cphone = getIntent().getStringExtra("cphone");
        yynumber = getIntent().getStringExtra("yynumber");
        if (name!=null||phone!=null||cphone!=null||yynumber!=null){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    JSONObject object = new JSONObject();
                    try {
                        object.put("KAA02",name);
                        object.put("KLA06",phone);
                        object.put("KLA07",cphone);
                        object.put("KYA11",yynumber);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    String json = object.toString();
                    String result = NetWorkUtils.getCount(baseClass.find_JZ_CUSTOMER_URL+1,json);
                    Log.d("ccc",result);
                    list = CoorCustomerJson.jsonVisitMessage(result);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (list!=null){
                                adapter = new ListViewAdapter(CustomerJZSeacherActivity.this,list);
                                listView.setAdapter(adapter);
                                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                        GetCustumer.create();
                                        GetCustumer.customers = list.get(position-1);
                                        Intent intent = new Intent(CustomerJZSeacherActivity.this,DetileSeacherCustomerActivity.class);
                                        startActivity(intent);
                                    }
                                });
                            }
                        }
                    });
                }
            }).start();
        }
    }
    @Override
    public void onLoad() {
        loadData(AutoListView.LOAD);
    }

    @Override
    public void onRefresh() {
        loadData(AutoListView.REFRESH);
    }
    class LoadTask extends AsyncTask<Void,Integer,Integer> {
        Message msg = handler.obtainMessage();
        @Override
        protected Integer doInBackground(Void... voids) {
            int what = 1;
            msg.what = what;
            page=page+1;
            JSONObject object = new JSONObject();
            try {
                object.put("KAA02",name);
                object.put("KLA06",phone);
                object.put("KLA07",cphone);
                object.put("KYA11",yynumber);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            String json = object.toString();
            String result = NetWorkUtils.getCount(baseClass.find_JZ_CUSTOMER_URL+page,json);
            alist = CoorCustomerJson.jsonVisitMessage(result);
            return null;
        }
        @Override
        protected void onPostExecute(Integer integer) {
            if (alist!=null){
                msg.obj = alist;
                handler.sendMessage(msg);
            }else {
                msg.obj = alist;
                handler.sendMessage(msg);
                Toast.makeText(CustomerJZSeacherActivity.this, "无更多数据", Toast.LENGTH_SHORT).show();
            }
            super.onPostExecute(integer);
        }
    }
    class UpdateTextTask extends AsyncTask<Void,Integer,Integer> {
        Message msg = handler.obtainMessage();
        @Override
        protected Integer doInBackground(Void... voids) {
            int what = 0;
            msg.what = what;
            page =1;
            JSONObject object = new JSONObject();
            try {
                object.put("KAA02",name);
                object.put("KLA06",phone);
                object.put("KLA07",cphone);
                object.put("KYA11",yynumber);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            String json = object.toString();
            String result = NetWorkUtils.getCount(baseClass.find_JZ_CUSTOMER_URL+1,json);
            alist = CoorCustomerJson.jsonVisitMessage(result);
            return null;
        }

        @Override
        protected void onPostExecute(Integer integer) {
            if (alist!=null){
                listView.setVisibility(View.VISIBLE);
                msg.obj = alist;
                handler.sendMessage(msg);
            }else {
                listView.setVisibility(View.GONE);
                Toast.makeText(CustomerJZSeacherActivity.this, "无数据", Toast.LENGTH_SHORT).show();
            }
            super.onPostExecute(integer);
        }
    }
    private void loadData(int refresh) {
        if (refresh== AutoListView.REFRESH){
            UpdateTextTask updateTextTask = new UpdateTextTask();
            updateTextTask.execute();
        }else if(refresh== AutoListView.LOAD){
            LoadTask loadTask = new LoadTask();
            loadTask.execute();
        }

    }
    private void showPopupWindow() {
        View contentView = LayoutInflater.from(CustomerJZSeacherActivity.this).inflate(
                R.layout.popowindow_customer_seacher, null);

        mPopWindow = new PopupWindow(contentView);
        mPopWindow.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        mPopWindow.setHeight( LinearLayout.LayoutParams.WRAP_CONTENT);

        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = contentView.getMeasuredWidth();    //  获取测量后的宽度
        int popupHeight = contentView.getMeasuredHeight();  //获取测量后的高度
        int[] location = new int[2];
        btn_seacher.getLocationOnScreen(location);
        mPopWindow.setAnimationStyle(R.style.contextMenuAnim);
        mPopWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.pop_bg));
        mPopWindow.setTouchable(true);
        mPopWindow.setOutsideTouchable(true);   //设置外部点击关闭ppw窗口
        mPopWindow.setFocusable(true);
        mPopWindow.update();
        mPopWindow.showAsDropDown(btn_seacher);
    }
}
